<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { getTransferTaskUserTree } from '@/api/system/user'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  taskId: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['update:modelValue', 'submit'])

watch(
  () => props.modelValue,
  val => {
    if (val) {
      // 打开时初始化数据
      getUserList()
    }
  }
)
const ruleFormRef = ref(null)
const formData = ref<any>({
  toUserId: undefined,
  opinion: undefined,
})
const rules = {
  toUserId: [{ required: true, message: '请选择用户', trigger: ['blur', 'change'] }],
  opinion: [{ required: true, message: '请输入转办原因', trigger: ['blur', 'change'] }],
}
const userList = ref<any[]>([])

const open = computed({
  get() {
    return props.modelValue
  },
  set() {
    emit('update:modelValue', false)
  },
})
const setDisabled = (list: any[]) => {
  return list.map(item => {
    if (item.children && item.children.length > 0) {
      item.children = setDisabled(item.children)
    }
    if (item.type === '2') {
      item.disabled = false
    } else {
      item.disabled = true
    }
    return item
  })
}
const getUserList = async () => {
  const res = await getTransferTaskUserTree()
  userList.value = setDisabled(res.data || [])
}

const handleSubmit = (formName: string) => {
  ruleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const params = {
        ...formData.value,
        taskId: props.taskId,
        action: '0', // 转办
      }

      // 返回选择用户id和转办原因
      emit('submit', params)
      formData.value = {
        toUserId: undefined,
        opinion: undefined,
      }
    }
  })
}
</script>

<template>
  <div>
    <el-dialog
      title="转办"
      v-model="open"
      width="700px"
      :before-close="
        () => {
          open = false
        }
      ">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="formData"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm">
        <el-form-item label="用户" prop="toUserId">
          <el-tree-select
            v-model="formData.toUserId"
            :data="userList"
            :props="{
              children: 'children',
              label: 'name',
              value: 'id',
            }"
            filterable
            clearable
            :render-after-expand="false" />
        </el-form-item>
        <el-form-item label="转办原因" prop="opinion">
          <el-input v-model="formData.opinion" type="textarea" :rows="4" placeholder="请输入转办原因"></el-input>
        </el-form-item>
        <div class="form-footer">
          <el-button type="primary" @click="handleSubmit('ruleFormRef')">确定</el-button>
          <el-button @click="open = false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped></style>
